package com.lx.huimail.fragment;

import android.app.AlertDialog;
import android.app.Dialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.text.Editable;
import android.text.TextWatcher;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageButton;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.google.gson.Gson;
import com.lx.huimail.MyApplication;
import com.lx.huimail.R;
import com.lx.huimail.activity.ChaoshiActivity;
import com.lx.huimail.activity.MoneyDetialActivity;
import com.lx.huimail.activity.MoneyWaterActivity;
import com.lx.huimail.activity.SafeSetActivity;
import com.lx.huimail.activity.SearchActivity;
import com.lx.huimail.activity.YaoqingmaActivity;
import com.lx.huimail.configs.Config;
import com.zhy.http.okhttp.OkHttpUtils;
import com.zhy.http.okhttp.callback.StringCallback;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import java.math.BigDecimal;
import java.text.DecimalFormat;
import java.util.HashMap;
import java.util.Map;

import okhttp3.Call;


/**
 * A simple {@link Fragment} subclass.
 */
public class UserFragment extends Fragment implements View.OnClickListener{

    private LinearLayout lly_detial,lly_water,lly_safeset,lly_yaoqingma,lly_search,lly_chaoshi;
    private  RelativeLayout rl1;
    private String custid="";
    double money;
    TextView jine;
    Button tixian;
    ImageButton imageButton;
    TextView zhuangtai;
    TextView yujiesuan1;
    TextView yujiesuan;
    TextView daozhang;
    private AlertDialog dialog;
    private Button cancel;
    private EditText et1;
    private EditText et2;
    private TextView tv1;
    private Button ok;
    private String name;
    private String mo;
    private String linkerid;
    private String isrest;
    int flag = 0;
    String benyueprofit;
    String benyueprofit1;
    String upprofit1;
    String upprofit;
    String settlement;
    TextView ketixian,zhanyong;
    double c,m;

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        View view=inflater.inflate(R.layout.fragment_user, container, false);
        initView(view);
        SharedPreferences sharedPreferences=getActivity().getSharedPreferences("user",Context.MODE_PRIVATE);
        custid=sharedPreferences.getString("custid","-1111");
        getUserInfo();
        searchyue();
        searchCash();
        report();
        return view;
    }

    private void initView(View view){
        yujiesuan=(TextView)view.findViewById(R.id.yujiesuan);
        yujiesuan1=(TextView)view.findViewById(R.id.yujiesuan1);
        jine=(TextView)view.findViewById(R.id.jine);
        tixian=(Button)view.findViewById(R.id.tixian);
        lly_detial=(LinearLayout)view.findViewById(R.id.lly_detial);
        lly_water=(LinearLayout)view.findViewById(R.id.lly_water);
        lly_safeset=(LinearLayout)view.findViewById(R.id.lly_safeset);
        lly_yaoqingma=(LinearLayout)view.findViewById(R.id.lly_yaoqingma);
        lly_search=(LinearLayout)view.findViewById(R.id.lly_search);
        lly_chaoshi=(LinearLayout)view.findViewById(R.id.lly_chaoshi);
        rl1=(RelativeLayout)view.findViewById(R.id.rl1);
        imageButton=(ImageButton)view.findViewById(R.id.imageButton);
        zhuangtai=(TextView)view.findViewById(R.id.zhuangtai);
        lly_detial.setOnClickListener(this);
        lly_water.setOnClickListener(this);
        lly_safeset.setOnClickListener(this);
        lly_yaoqingma.setOnClickListener(this);
        lly_search.setOnClickListener(this);
        lly_chaoshi.setOnClickListener(this);
        tixian.setOnClickListener(this);
        rl1.setOnClickListener(this);
    }

    @Override
    public void onClick(View v) {

        switch (v.getId()){
            case R.id.lly_detial:
                startAct(MoneyDetialActivity.class);
                break;
            case R.id.lly_water:
                startAct(MoneyWaterActivity.class);
                break;
            case R.id.lly_search:
                Intent intent=new Intent(getActivity(),SearchActivity.class);
                intent.putExtra("settlement",settlement);
                startActivity(intent);
                break;
            case R.id.lly_safeset:
                startAct(SafeSetActivity.class);
                break;
            case R.id.lly_yaoqingma:
                startAct(YaoqingmaActivity.class);
                break;
            case R.id.lly_chaoshi:
                startAct(ChaoshiActivity.class);
                break;
            case R.id.rl1:
                if(isrest.equals("0")){
                    isRecovery();

                }else if (isrest.equals("1")){
                    rest();

                }
                break;
            case R.id.tixian:
                LayoutInflater inflater = getActivity().getLayoutInflater();
                View layout = inflater.inflate(R.layout.customdialog,
                        (ViewGroup)v.findViewById(R.id.customdialog));
                AlertDialog.Builder builder = new AlertDialog.Builder(getActivity());
                builder .setView(layout);
                dialog=builder.create();
                dialog.show();
                cancel=(Button)layout.findViewById(R.id.cancel);
                et1=(EditText)layout.findViewById(R.id.et1);
                et2=(EditText)layout.findViewById(R.id.et2);
                ketixian=(TextView)layout.findViewById(R.id.ketixian);
                zhanyong=(TextView)layout.findViewById(R.id.zhanyong);
                daozhang=(TextView)layout.findViewById(R.id.daozhang);
                ok=(Button)layout.findViewById(R.id.ok);
                cancel.setOnClickListener(new View.OnClickListener() {

                    @Override
                    public void onClick(View v) {
                        dialog.dismiss();

                    }
                });
                c=Double.valueOf(mo)-m;
                //ketixian.setText(mo);
                ketixian.setText(String.valueOf(c));
                zhanyong.setText(String.valueOf(m));

                et1.addTextChangedListener(new TextWatcher() {

                    @Override
                    public void onTextChanged(CharSequence s, int start, int before, int count) {
                        if (s.length() > 0) {
                            double d=Double.parseDouble(et1.getText().toString());
                            double f=d*0.0025;
                            BigDecimal bigDec = new BigDecimal(f);
                            double total = bigDec.setScale(2, BigDecimal.ROUND_HALF_UP).doubleValue();
                            DecimalFormat df = new DecimalFormat("0.00");
                           double db= d-Double.valueOf(df.format(total));
//                            BigDecimal bd = new BigDecimal(f);
//                            bd = bd.setScale(2, BigDecimal.ROUND_DOWN);
                            daozhang.setText(String.valueOf(db));
                        } else {
                            daozhang.setText("");
                        }
                    }

                    @Override
                    public void beforeTextChanged(CharSequence s, int start, int count, int after) {

                    }

                    @Override
                    public void afterTextChanged(Editable s) {
                    }
                });
                ok.setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        if (et1.getText().toString().equals("")){
                            dialog.dismiss();
                        } else{
                            if (Double.valueOf(et1.getText().toString())<100){
                                Toast.makeText(getContext(),"可提现金额不足100,无法提现",Toast.LENGTH_LONG).show();

                                return;
                            }
                            if (Double.valueOf(et1.getText().toString())>c){
                                Toast.makeText(getContext(),"可提现金额不足",Toast.LENGTH_LONG).show();
                            }else {
                                double f= Double.parseDouble( et1.getText().toString())-Double.parseDouble(daozhang.getText().toString());
                                HashMap<String, String> map = new HashMap<String, String>();
                                map.put("type", "6");
                                map.put("custid", custid);
                                map.put("custname", name);
                                map.put("tax", String.valueOf(f));
                                map.put("realmoney", daozhang.getText().toString());
                                map.put("money", et1.getText().toString());
                                map.put("note", et2.getText().toString());
                                Gson gson = new Gson();
                                String str = gson.toJson(map).toString();
                                OkHttpUtils
                                        .post()
                                        .url(Config.url + "cash/addCash.do")
                                        .addParams("data", str)
                                        .addParams("mobile", "true")
                                        .build()
                                        .execute(new StringCallback() {
                                            @Override
                                            public void onError(Call call, Exception e, int id) {
                                                Toast.makeText(getContext(), "服务器连接失败", Toast.LENGTH_SHORT).show();
                                            }

                                            @Override
                                            public void onResponse(String response, int id) {
                                                System.out.print("提现请求--" + response);
                                                if (response.equals("\"true\"")) {
                                                    Toast.makeText(getActivity(), "提现请求成功", Toast.LENGTH_SHORT).show();
                                                    dialog.dismiss();
                                                    searchCash();
                                                }
                                            }

                                        });
                            }
                        }
                    }
                });
                break;
        }
    }

    private void startAct(Class tClass ){
        startActivity(new Intent(getContext(),tClass));
    }
    private void rest(){
        HashMap<String,String> map=new HashMap<String, String>();
        map.put("linkerid","");
        map.put("id",custid);
        Gson gson=new Gson();
        String str=gson.toJson(map).toString();
        OkHttpUtils
                .post()
                .url(Config.url+"send/isRest.do")
                .addParams("data",str)
                .addParams("mobile","true")
                .build()
                .execute(new StringCallback() {
                    @Override
                    public void onError(Call call, Exception e, int id) {
                        System.out.print("连接失败=="+e.getMessage().toString());
                        //Toast.makeText(getContext(),"服务器连接失败",Toast.LENGTH_SHORT).show();
                    }

                    @Override
                    public void onResponse(String response, int id) {
                        System.out.print("申请休息=="+response);
                        if (response.equals("\"您是最后一个申请休息的配送员，请联系分销员确认\"")){
                            LayoutInflater inflater = getActivity().getLayoutInflater();
                            View layout = inflater.inflate(R.layout.customdialog1,
                                    (ViewGroup)getActivity().findViewById(R.id.customdialog));
                            AlertDialog.Builder builder = new AlertDialog.Builder(getActivity());
                            builder .setView(layout);
                            dialog=builder.create();
                            dialog.show();
                            tv1=(TextView)layout.findViewById(R.id.tv1);
                            tv1.setText(response.replace("\"",""));
                            ok=(Button)layout.findViewById(R.id.ok);
                            ok.setOnClickListener(new View.OnClickListener() {
                                @Override
                                public void onClick(View v) {
                                    dialog.dismiss();
                                }
                            });
                        }else{
                            imageButton.setBackgroundResource(R.drawable.status_quit);
                            zhuangtai.setText("休息");
                            isrest="0";
                            // getUserInfo();
                        }

                    }



                });
    }
    private void isRecovery(){
        HashMap<String,String> map=new HashMap<String, String>();
        map.put("id",custid);
        Gson gson=new Gson();
        String str=gson.toJson(map).toString();
        OkHttpUtils
                .post()
                .url(Config.url+"send/isRecovery.do")
                .addParams("data",str)
                .addParams("mobile","true")
                .build()
                .execute(new StringCallback() {
                    @Override
                    public void onError(Call call, Exception e, int id) {
                        //Toast.makeText(getContext(),"服务器连接失败",Toast.LENGTH_SHORT).show();
                    }

                    @Override
                    public void onResponse(String response, int id) {
                        System.out.print("申请工作=="+response);
                        if (response.equals("\"true\"")){
                            imageButton.setBackgroundResource(R.drawable.status_speaking);
                            zhuangtai.setText("工作");
                            isrest="1";
                            //getUserInfo();
                        }

                    }



                });
    }
    private void getUserInfo(){
        OkHttpUtils
                .post()
                .url(Config.url+"login/getCustInfo.do")
                .addParams("custid",custid)
                .addParams("mobile","true")
                .build()
                .execute(new StringCallback() {
                    @Override
                    public void onError(Call call, Exception e, int id) {
                        //Toast.makeText(getContext(),"服务器连接失败",Toast.LENGTH_SHORT).show();
                    }

                    @Override
                    public void onResponse(String response, int id) {
                        System.out.print("个人信息=="+response);
                        try {
                            JSONArray jsonArray=new JSONArray(response);
                            name=jsonArray.getJSONObject(0).getString("name");
                            isrest=jsonArray.getJSONObject(0).getString("isrest");
                            JSONArray a1=jsonArray.getJSONObject(1).getJSONArray("addrlist");
                            linkerid=a1.getJSONObject(0).getString("linkerid");
                            if (isrest.equals("1")){
                                imageButton.setBackgroundResource(R.drawable.status_speaking);
                                zhuangtai.setText("工作");
                            }else if (isrest.equals("0")){
                                imageButton.setBackgroundResource(R.drawable.status_quit);
                                zhuangtai.setText("休息");
                            }
                        }catch(JSONException e){
                            e.printStackTrace();
                        }
                    }
                });
    }
    private void searchyue(){
        HashMap<String,String> map=new HashMap<String, String>();
        map.put("departid",custid);
        Gson gson=new Gson();
        String str=gson.toJson(map).toString();
        OkHttpUtils
                .post()
                .url(Config.url+"cash/searchyue.do")
                .addParams("data",str)
                .addParams("mobile","true")
                .build()
                .execute(new StringCallback() {
                    @Override
                    public void onError(Call call, Exception e, int id) {
                        // Toast.makeText(getContext(),"服务器连接失败",Toast.LENGTH_SHORT).show();
                    }


                    @Override
                    public void onResponse(String response, int id) {
                        System.out.print("总钱数--"+response);
                        try {
                            JSONArray jsonArray=new JSONArray(response);
                            String mon=jsonArray.getJSONObject(0).getString("money");
                            money=Double.valueOf(mon);
                        } catch (JSONException e) {
                            e.printStackTrace();
                        }

                    }
                });
    }
    private void searchCash(){
        HashMap<String,String> map=new HashMap<String, String>();
        map.put("custidEQ",custid);
        map.put("typeEQ","6");
        map.put("isbudgetEQ","0");
        Gson gson=new Gson();
        String str=gson.toJson(map).toString();
        OkHttpUtils
                .post()
                .url(Config.url+"cash/pingtaisearchCash.do")
                .addParams("data",str)
                .addParams("mobile","true")
                .addParams("page","1")
                .addParams("rows","10000000")
                .addParams("flag","1")
                .build()
                .execute(new StringCallback() {
                    @Override
                    public void onError(Call call, Exception e, int id) {
                        //Toast.makeText(getContext(),"服务器连接失败",Toast.LENGTH_SHORT).show();
                    }


                    @Override
                    public void onResponse(String response, int id) {
                        System.out.print("占用钱数--"+response);
                        double sum=0.00;
                        try {
                            JSONObject o1=new JSONObject(response);
                            JSONArray a1=o1.getJSONArray("rows");
                            for(int i=0;i<a1.length();i++){
                                String s=a1.getJSONObject(i).getString("money");
                                double su=Double.valueOf(s);
                                sum=sum+su;
                            }

                        } catch (JSONException e) {
                            e.printStackTrace();
                        }
                        // double m=money-sum;
                        m=sum;
                        //jine.setText(m+"");
                    }

                });

    }
    private void report(){
        HashMap<String,String> map=new HashMap<String, String>();
        map.put("custidEQ",custid);
        Gson gson=new Gson();
        String str=gson.toJson(map).toString();
        OkHttpUtils
                .post()
                .url(Config.url+"report/loadpeisongemployeeprofit.do")
                .addParams("data",str)
                .addParams("mobile","true")
                .addParams("page","1")
                .addParams("rows","20")
                .addParams("flag","1")
                .build()
                .execute(new StringCallback() {
                    @Override
                    public void onError(Call call, Exception e, int id) {
                        System.out.print("预结算失败==" + e.getMessage().toString());
                        //Toast.makeText(getContext(), "服务器连接失败", Toast.LENGTH_SHORT).show();
                    }


                    @Override
                    public void onResponse(String response, int id) {
                        System.out.print("预结算--" + response);
                        try{
                            JSONObject o1=new JSONObject(response);
                            JSONArray jsonArray=o1.getJSONArray("rows");
                            if (jsonArray.length()==0){
                                benyueprofit="0";
                                upprofit="0";
                                mo="0";
                            }else {
                                settlement = jsonArray.getJSONObject(0).getString("id");
                                if (jsonArray.getJSONObject(0).getString("money").equals("null")) {
                                    mo = "0";
                                } else {
                                    mo = jsonArray.getJSONObject(0).getString("money");
                                }
                                if (jsonArray.getJSONObject(0).getString("benyueprofit").equals("null")) {
                                    benyueprofit = "0";
                                } else {
                                    benyueprofit = jsonArray.getJSONObject(0).getString("benyueprofit");
                                }
                                if (jsonArray.getJSONObject(0).getString("upprofit").equals("null")) {
                                    upprofit = "0";
                                } else {
                                    upprofit = jsonArray.getJSONObject(0).getString("upprofit");
                                }
                                DecimalFormat df   =new   DecimalFormat("0.00");
                                benyueprofit1=df.format(Double.parseDouble(benyueprofit));
                                upprofit1=df.format(Double.parseDouble(upprofit));
                            }
                        }catch(JSONException e){
                            e.printStackTrace();
                        }
                        jine.setText("可提现金额："+"¥"+mo);
                        yujiesuan.setText("本月预结算："+"¥"+benyueprofit1+"");
                        yujiesuan1.setText("上月预结算："+"¥"+upprofit1+"");

                    }

                });
    }
}
